package com.deng.mina.server;

import com.deng.mina.common.protocol.ProtocolPack;
import com.deng.mina.common.util.LogUtils;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.util.Date;

/**
 * @Project
 * @Module
 * @JDK_Vserion 1.8
 * @Author DengLibin
 * @Email dlb@smarthse.cn
 * @Desc handler
 * @since 2019/9/17 0017 14:25
 */
public class ServerHandler extends IoHandlerAdapter {
    /**
     * 连接异常时
     * @param session
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        super.exceptionCaught(session, cause);
        LogUtils.warn("连接异常");
    }

    /**
     * session关闭
     * @param session
     * @throws Exception
     */
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        LogUtils.info("session 关闭");
    }

    /**
     * session创建
     * @param session
     * @throws Exception
     */
    @Override
    public void sessionCreated(IoSession session) throws Exception {
       LogUtils.info("session 创建");
    }

    /**
     * 会话 空闲
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
       LogUtils.info("session 空闲");
    }

    /**
     * 会话打开
     * @param session
     * @throws Exception
     */
    @Override
    public void sessionOpened(IoSession session) throws Exception {
       LogUtils.info("session 打开");
    }

    /**
     * 接收到数据
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        LogUtils.info("服务端接收到数据："+message.toString());
        if(message.equals("exit")){
            session.closeOnFlush();
            return;
        }
        session.write(new ProtocolPack((byte) 2, "我是服务端")); // 发送数据
    }
}
